// src/pages/room/index.tsx
import styles from "@styles/room.module.scss";
import { Helmet } from "react-helmet";
import Header from "@shared/header";
import { PictureOutline, RightOutline, StarFill, StarOutline } from "antd-mobile-icons";
import React, {useEffect, useRef, useState} from "react";
import TextareaAutosize from "react-textarea-autosize";
import {useNavigate, useSearchParams} from "react-router-dom";
import { io, Socket } from "socket.io-client";
import {useTypedSelector} from "@store/index";
import {selectAuth} from "@store/slices/authSlice";
import {nanoid} from "@reduxjs/toolkit";
import {MsgType} from "@enums/room";
import Message from "@pages/room/widgets/message";
import {useOrderDetailQuery} from "@store/apiSlice/consultApiSlice";
import Status from "@pages/room/widgets/status";
import Action from "@pages/room/widgets/action";
import Say_doctor from "@pages/room/widgets/say_doctor";
import Say_patient from "@pages/room/widgets/say_patient";
import {PullToRefresh} from "antd-mobile";

export default function Room() {
    // 用于实现页面跳转
    const navigate = useNavigate();
    //用于存储socket实例对象
    const socket = useRef<Socket | null>()
    //用于获取用户登录凭据
    const {token} = useTypedSelector(selectAuth)
    //获取路由参数
    const [searchParams] = useSearchParams();
    //获取订单id
    const orderId = searchParams.get("orderId")
    // 用于保存默认聊天记录
    const [messages, setMessages] = useState<Message[]>([]);
    //用于获取订单详细信息
    const {data , refetch} = useOrderDetailQuery(orderId!)
    // 用于获取 .page 元素
    const pageElement = useRef<null | HTMLDivElement>(null);
    // 用于记录当前聊天消息组中的最早聊天记录的时间
    const [lastTime, setLastTime] = useState("");
    // 用于控制 loading 是否展示
    const wp = useRef<{ p?: Promise<void>; resolve?: () => void }>({});
    //socket 连接与销毁
    useEffect(()=>{
        //创建socket实例
        socket.current = io(process.env.REACT_APP_BASE_URL!,{
            auth:{
                //只有登录以后才能聊天
                token: `Bearer ${token}`,
            },
            query:{
                //通过订单id绑定医生和患者
                orderId
            }
        })
        //监听连接成功事件
        socket.current.on("connect",()=> console.log("socket连接成功"))
        // 监听连接失败事件
        socket.current.on("connect_error", (error) => console.log(error.message));
        // 监听连接断开事件
        socket.current.on("disconnect", () => console.log("连接已断开"));
        // 接收默认聊天记录
        // 接收默认聊天记录
        socket.current.on("chatMsgList", ({ data }: { data: TimeMessages[] }) => {
            // 历史聊天记录获取成功
            wp.current.resolve?.();
            // 遍历以时间段分割的消息组
            data.forEach((group,index) =>{
                if (index === 0) setLastTime(group.createTime)
                    // 保存消息
                    setMessages((messages) => [
                        // 创建普通系统消息 用于存储消息组的时间
                        {
                            id: nanoid(),
                            from: "sys",
                            fromAvatar: "",
                            to: "",
                            toAvatar: "",
                            createTime: group.createTime,
                            msgType: MsgType.Notify,
                            msg: {
                                content: group.createTime,
                            },
                        },
                        // 存储消息列表
                        ...group.items,
                        ...messages,
                    ])
            }
            // 记录当前聊天消息组中最早的消息创建时间


            );

        });
        //监听订单状态变化
        socket.current.on("statusChange",()=>{
            //重新获取订单详情
            refetch()
        })
        //接收消息
        socket.current.on("receiveChatMsg",(message:Message)=>{
            //存储消息
            setMessages((messages)=>[...messages,message])
            // 等待页面渲染完成后滚动
            requestIdleCallback(scrollToBottom);
        })
    },[orderId,refetch,token])
    // 滚动到最新位置
    const scrollToBottom = () => {
        // 滚动到最新位置
        pageElement.current?.scrollTo({
            top: pageElement.current.scrollHeight,
        });
    };
    // 获取用户 id
    const { id } = useTypedSelector(selectAuth);
    //用于发送文字信息
    const sendMsg = (text:string) =>{

        socket.current?.emit("sendChatMsg",{
            from:id,
            to:data?.data.docInfo?.id,
            msgType: MsgType.MsgText,
            msg: {content: text}
        })
    }
    // 发送图片消息
    const sendImage = (image: Image) => {
        socket.current?.emit("sendChatMsg", {
            from: id,
            to: data?.data.docInfo?.id,
            msgType: MsgType.MsgImage,
            msg: { picture: image },
        });
    };
    // 用于更新本地评价
    const updateEvaluate = (score: number) => {
        // 获取未评价消息索引
        const index = messages.findIndex(
            (message) => message.msgType === MsgType.CardEvaForm
        );
        const message = messages[index];
        // 更新消息
        setMessages([
            ...messages.slice(0, index),
            {
                ...message,
                msgType: MsgType.CardEva,
                msg: { ...message.msg, evaluateDoc: { score } },
            },
            ...messages.slice(index + 1),
        ]);
    };
    return (
        <>
            <Helmet>
                <title>优医问诊-医生问诊室</title>
            </Helmet>
            <Header title="医生问诊室" backHandler={() => navigate("/")}/>
            <div className={styles.page} ref={pageElement}>
                <Status status={data?.data.status} countDown={data?.data.countdown}/>
                <PullToRefresh
                    onRefresh={async () => {
                        // 发出获取历史聊天记录的请求
                        socket.current?.emit("getChatMsgList", 20, lastTime, orderId);
                        // 存储 promise 和其对应的 resolve
                        wp.current.p = new Promise(
                            (resolve) => (wp.current.resolve = resolve)
                        );
                        // 等待服务端响应历史聊天记录
                        await wp.current.p;
                    }}
                >
                    <Message messages={messages} updateEvaluate={updateEvaluate} orderId={data?.data.id} docId={data?.data.docInfo?.id}/>
                </PullToRefresh>
            </div>
            <Action  status={data?.data.status} sendMsg={sendMsg} sendImage={sendImage} />
        </>
    );
}